<script setup>

import request from "@/utils/request.js";
import TitleLabel from "@/components/TitleLabel.vue";
import useCompanyStore from "@/store/modules/company.js"
import BarCharts from "@/views/portal/chartCard/BarCharts.vue";
import PieCharts from "@/views/portal/chartCard/PieCharts.vue";

const companyStore = useCompanyStore();

const props = defineProps({
  title: {
    type: String,
    required: true
  },
  chartType: {
    type: String,
    default: 'pie'
  },
  groupBy: {
    type: String
  },
  nameMapping: {
    type: Object,
  }
});

const companyId = ref(null);
const statisticsType = ref('count');
const url = '/portal/chart/assetDistribute';
const data = ref([]);

function getValueFromUrl() {

  if (url) {
    request({
      url: url,
      method: "get",
      params: {
        companyId: companyId.value,
        type: statisticsType.value,
        groupBy: props.groupBy,
      }
    }).then(res => {
      const nameMapping = props.nameMapping;
      data.value = res.data.map(function (item) {
        if (!item.name) {
          item.name = '未知'
        } else {
          if (nameMapping && nameMapping[item.name]) {
            item.name = nameMapping[item.name];
          }
        }
        return item;
      });
    })
  }

}

const type = ref('count');
const companyList = computed(()=> {
  return companyStore.getList();
});

onMounted(() => {
  getValueFromUrl()
})

</script>

<template>
  <el-col :span="8">
    <el-card shadow="always" style="padding-bottom: 20px;font-size: 14px">
      <div class="topbar">
        <div class="title">
          <title-label>{{title}}</title-label>
        </div>
        <div class="action">
          <el-radio-group  v-model="statisticsType" style="margin-right: 10px;" @change="getValueFromUrl">
            <el-radio-button size="small" value="count">数量</el-radio-button>
            <el-radio-button size="small" value="amount">金额</el-radio-button>
          </el-radio-group>
          <el-select size="small" clearable v-model="companyId" style="width: 100px;margin-right: 10px;" placeholder="所有公司" @change="getValueFromUrl">
            <el-option v-for="c in companyList" :label="c.name" :value="c.id"></el-option>
          </el-select>
          <el-button size="small">
            <span><i class="el-icon-delete"></i></span>
          </el-button>
        </div>

      </div>
      <BarCharts v-if="chartType==='bar'" :data="data"></BarCharts>
      <PieCharts v-if="chartType==='pie'" :data="data"></PieCharts>
    </el-card>
  </el-col>
</template>

<style scoped lang="scss">
  .el-card {
    margin-bottom: 10px;
    .topbar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .action {
        display: flex;
        flex-shrink: 0;
        align-items: center;
      }
    }
  }

  .el-radio-group {
    /* align-items: center; */
    display: inline-block;
    flex-wrap: nowrap;
    font-size: 0;
    white-space: nowrap;
  }
</style>